package com.zhny.project.exec.display.controller;

import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.zhny.common.utils.file.FileUploadUtils;
import com.zhny.framework.config.RuoYiConfig;
import com.zhny.project.exec.record.service.IRecordService;
import com.zhny.project.system.config.domain.Config;
import com.zhny.test.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.zhny.framework.aspectj.lang.annotation.Log;
import com.zhny.framework.aspectj.lang.enums.BusinessType;
import com.zhny.project.exec.display.domain.AlgorithmDisplay;
import com.zhny.project.exec.display.service.IAlgorithmDisplayService;
import com.zhny.framework.web.controller.BaseController;
import com.zhny.framework.web.domain.AjaxResult;
import com.zhny.common.utils.poi.ExcelUtil;
import com.zhny.framework.web.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 算法演示Controller
 *
 * @author yanqun
 * @date 2019-11-25
 */
@Controller
@RequestMapping("/exec/display")
public class AlgorithmDisplayController extends BaseController
{
    private String prefix = "exec/display";

    @Autowired
    private IAlgorithmDisplayService algorithmDisplayService;

    @Autowired
    private IRecordService recordService;

    @RequiresPermissions("exec:display:view")
    @GetMapping()
    public String display()
    {
        return prefix + "/display";
    }

    /**
     * 查询算法演示列表
     */
    @RequiresPermissions("exec:display:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(AlgorithmDisplay algorithmDisplay)
    {
        startPage();
        List<AlgorithmDisplay> list = algorithmDisplayService.selectAlgorithmDisplayList(algorithmDisplay);
        return getDataTable(list);
    }

    /**
     * 导出算法演示列表
     */
    @RequiresPermissions("exec:display:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(AlgorithmDisplay algorithmDisplay)
    {
        List<AlgorithmDisplay> list = algorithmDisplayService.selectAlgorithmDisplayList(algorithmDisplay);
        ExcelUtil<AlgorithmDisplay> util = new ExcelUtil<AlgorithmDisplay>(AlgorithmDisplay.class);
        return util.exportExcel(list, "display");
    }

    /**
     * 新增算法演示
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存算法演示
     */

//    @PostMapping("/add")
//    @ResponseBody
//    public AjaxResult addSave(AlgorithmDisplay algorithmDisplay, MultipartFile  multipartFile)
//            throws IOException {
//
//        return toAjax(algorithmDisplayService.insertAlgorithmDisplay(algorithmDisplay));
//    }

    @PostMapping("/storages")
    @ResponseBody
    public AjaxResult storages(AlgorithmDisplay algorithmDisplay, MultipartFile  multipartFile)
            throws IOException {
        String filename = multipartFile.getOriginalFilename();
        StringBuilder result = new StringBuilder();

        int flag = 0;
        String dataFilePath = "";
        int mun = 0;

        try {
            //存放本地
            String filepath = RuoYiConfig.getDataPath();
            String a = filepath;
            int length = a.length() - 1;

            dataFilePath = FileUploadUtils.upload(filepath, multipartFile);
            String sdd = dataFilePath.substring(length);

            mun =  recordService.storagesService(dataFilePath, algorithmDisplay);
        } catch (Exception e) {
            System.err.println(e);
        }

        return toAjax(mun);
    }
    @PostMapping("/file")
    @ResponseBody
    public AjaxResult file(AlgorithmDisplay algorithmDisplay, MultipartFile  multipartFile,String algorithmId)
            throws IOException {
        String filename = multipartFile.getOriginalFilename();
        StringBuilder result = new StringBuilder();
        int flag = 0;
        String dataFilePath = "";
        try {
            //存放本地
            String filepath = RuoYiConfig.getDataPath();
            dataFilePath = FileUploadUtils.upload(filepath, multipartFile);
        } catch (Exception e) {
            System.err.println(e);
        }

//        二次
        Map<String,Object> map = new HashMap<String,Object>();
        String resultFilePath = RuoYiConfig.getResultPath();
        int count = 0;

        if ("A01".equals(algorithmId)) {
            //主成分分析算法
            PCAUtil.exc(dataFilePath, resultFilePath + "/pcautil.txt");
            count = 1;
        } else if("A02".equals(algorithmId)) {
            //皮尔森相关分析
            PearsonUtil.exc(dataFilePath, resultFilePath + "/pearson.txt");
            count = 1;
        } else if("A03".equals(algorithmId)) {
            //斯皮克曼关联分析
            SpearmanUtil.exc(dataFilePath, resultFilePath + "/spearman.txt");
            count = 1;
        } else if("A04".equals(algorithmId)) {
            //线性回归算法
            LinearRegressionUtil.exc(dataFilePath, resultFilePath + "/linearregress.txt");
            count = 1;
        } else if("A05".equals(algorithmId)) {
            //决策树算法
            DecisionTreeUtil.exc(dataFilePath, resultFilePath + "/decisiontree.txt");
            count = 1;
        } else if("A06".equals(algorithmId)) {
            //随机森林分类算法
//            libsvm数据格式的txt
            RandomForestClassificationUtil.exc(dataFilePath, resultFilePath+"/randomforest.txt");
            count = 1;
        } else if("A07".equals(algorithmId)) {
            //朴树贝叶斯
//            libsvm数据格式的txt
            NaiveBayesUtil.exc(dataFilePath, resultFilePath+"/naivebayes.txt");
            count = 1;
        } else if("A08".equals(algorithmId)) {
            //均值聚类
            KMeansUtil.exc(dataFilePath, resultFilePath+"/kmeans.txt");
            count = 1;
        } else if("A09".equals(algorithmId)) {
            //协同过滤
            FPGrowthUtil.exc(dataFilePath, resultFilePath+"/fpgrowth.txt");
            count = 1;
        } else if("A10".equals(algorithmId)) {
            LogisticRegressionUtil.exc(dataFilePath, resultFilePath + "/logisticregression.txt");
            //逻辑回归
            count = 1;
        }

        //map.put("count",count);
        return  toAjax(count);
    }

    /**
     * 修改算法演示
     */
    @GetMapping("/edit/{algorithmId}")
    public String edit(@PathVariable("algorithmId") String algorithmId, ModelMap mmap)
    {
        AlgorithmDisplay algorithmDisplay = new AlgorithmDisplay();
        algorithmDisplay.setAlgorithmId(algorithmId);
//        if("A01".equals(algorithmId) ){
//            return prefix + "/editpcautil";
////            editpcautil
//        }else if ("A02".equals(algorithmId)){
//            return prefix + "/editPearson";
//        }else {
          mmap.put("algorithmDisplay", algorithmDisplay);

          return prefix + "/edit";
//        }
    }

//    @GetMapping("/uploads/{algorithmId}")
////    public String uploads(@PathVariable("algorithmId") String algorithmId, ModelMap mmap)
////    {
////        mmap.put("algorithmId",algorithmId);
////        return "/edit";
////    }



    /**
     * 修改保存算法演示
     */
    @RequiresPermissions("exec:display:edit")
    @Log(title = "算法演示", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(AlgorithmDisplay algorithmDisplay)
    {
        return toAjax(algorithmDisplayService.updateAlgorithmDisplay(algorithmDisplay));
    }

    /**
     * 删除算法演示
     */
    @RequiresPermissions("exec:display:remove")
    @Log(title = "算法演示", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(algorithmDisplayService.deleteAlgorithmDisplayByIds(ids));
    }

    //    执行算法演示
    @RequestMapping("/calculate")
    @ResponseBody
    public Map<String,Object> searchUse(String algorithmId) {
        Map<String,Object> map = new HashMap<String,Object>();
        String resultFilePath = RuoYiConfig.getResultPath();
        int count = 0;

        if ("A01".equals(algorithmId)) {
            //主成分分析算法
            PCAUtil.exc(null, resultFilePath + "/pcautil.txt");
            count = 1;
        } else if("A02".equals(algorithmId)) {
            //皮尔森相关分析
            PearsonUtil.exc(null, resultFilePath + "/pearson.txt");
            count = 1;
        } else if("A03".equals(algorithmId)) {
            //斯皮克曼关联分析
            SpearmanUtil.exc(null,resultFilePath + "/spearman.txt");
            count = 1;
        } else if("A04".equals(algorithmId)) {
            //线性回归算法
            LinearRegressionUtil.exc(null, resultFilePath + "/linearregress.txt");
            count = 1;
        } else if("A05".equals(algorithmId)) {
            //决策树算法
            DecisionTreeUtil.exc(null, resultFilePath+"/decisiontree.txt");
            count = 1;
        } else if("A06".equals(algorithmId)) {
            //随机森林分类算法
            RandomForestClassificationUtil.exc(null, resultFilePath+"/randomforest.txt");
            count = 1;
        } else if("A07".equals(algorithmId)) {
            //朴树贝叶斯
            NaiveBayesUtil.exc(null, resultFilePath+"/naivebayes.txt");
            count = 1;
        } else if("A08".equals(algorithmId)) {
            //均值聚类
            KMeansUtil.exc(null, resultFilePath+"/kmeans.txt");
            count = 1;
        }else if("A09".equals(algorithmId)){
            //协同过滤
            FPGrowthUtil.exc(null, resultFilePath+"/fpgrowth.txt");
            count = 1;
        } else if("A10".equals(algorithmId)) {
            LogisticRegressionUtil.exc(null, resultFilePath + "/logisticregression.txt");
            //逻辑回归
            count = 1;
        }

        map.put("count",count);
        return  map;
    }

    @GetMapping("/resultdown/{filename}")
    public void resultdown(@PathVariable("filename") String filename, HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        String fileName = filename;
        response.setHeader("content-disposition", "attachment;filename=" + fileName);
        InputStream in=null;
        OutputStream out=null;
        try {
            in=new FileInputStream(RuoYiConfig.getResultPath() + "/" + filename);
            int len = 0;
            byte[] buffer = new byte[1024];
            out = response.getOutputStream();
            while ((len = in.read(buffer)) > 0) {
                out.write(buffer,0,len);
            }
        }catch (FileNotFoundException e){
            e.printStackTrace();
        }finally{
            in.close();
            out.close();
        }
    }
}


